//
//  ErandChangeApproveListViewController.m
//  KIASupervisory
//
//  Created by tan_xin on 14-7-7.
//  Copyright (c) 2014年 MyCompany. All rights reserved.
//

#import "ErandChangeApproveListViewController.h"
#import "ErandChangeApproveDetailViewController.h"
#import "RejectViewController.h"
#import "MTStatusBarOverlay.h"
#import "LStoreProblemListViewController.h"

@interface ErandChangeApproveListViewController () <UIActionSheetDelegate,RejectViewDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (nonatomic, strong) NSMutableArray *applyList;
@property (nonatomic, assign) NSInteger selectedRow;

@end

@implementation ErandChangeApproveListViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.applyList = [NSMutableArray array];
    self.selectedRow = -1;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated {
    
    self.showLeftBtn = YES;
    self.showRightBtn = NO;
    self.title = @"出差变更审批";
    
    [super viewWillAppear:animated];
    
    [self performSelector:@selector(getErandChangeApplyList) withObject:nil afterDelay:0.3];
}

- (void)refreshViewByReloadData {
    [self getErandChangeApplyList];
}

- (void)leftNavItemAction:(id)sender {
    AppDelegate *dele = [AppDelegate sharedDelegate];
    DDMenuController *menuVC = dele.ddLeftMenu;
    [menuVC showLeft:nil];
}

//查询当前领导的出差变更审批列表
- (void)getErandChangeApplyList {
    if (!self.isRefreshing) {
        self.isRefreshing = YES;
        [self.applyList removeAllObjects];
        
        UserInfo *user = [UserInfo instance];
        NSString *yhm = [user.info objectForKeyOrNil:@"yhm"];
        NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                               yhm,@"gh", nil];
        [self.networkManager requestWithMethod:showUserInfoByChang parameter:param delegate:self];
        [self.HUD show:YES];
    }
}

#pragma mark - NetworkManagerDelegate
- (void)network:(NetworkManager *)net methodId:(RequestMethodId)methodId didRequestFinishedWithResult:(id)data {
    [self.HUD hide:YES];
    [self endRefresh];
    self.isRefreshing = NO;
    
    if (methodId == showUserInfoByChang) {
        if ([data isKindOfClass:[NSDictionary class]]) {
            int code = [[data objectForKeyOrNil:@"code"] integerValue];
            if (code == 0) {
                [self.applyList removeAllObjects];
                
                if ([data count] > 0) {
                    id dataObject = [data objectForKeyOrNil:@"data"];
                    if ([dataObject isKindOfClass:[NSArray class]]) {
                        [self.applyList addObjectsFromArray:dataObject];
                    }
                }
                
            } else {
                NSString *msg = [data objectForKeyOrNil:@"msg"];
                if ([msg  length] == 0) {
                    msg = @"出差变更申请列表获取失败，请稍后重试";
                }
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                                message:msg
                                                               delegate:nil
                                                      cancelButtonTitle:@"确定"
                                                      otherButtonTitles:nil];
                [alert show];
            }
        }
        
        [self.tableView reloadData];
        
    } else if (methodId == leaderExamineApplyChange) { //审批通过
        if ([data isKindOfClass:[NSDictionary class]]) {
            int code = [[data objectForKeyOrNil:@"code"] integerValue];
            if (code == 0) {
                if ([data count] > 0) {
                    id dataObject = [data objectForKeyOrNil:@"data"];
                    NSInteger resultCode = [[dataObject objectForKeyOrNil:@"result"] integerValue];
                    if (resultCode == 1) {
//                        MTStatusBarOverlay *overlay = [MTStatusBarOverlay sharedInstance];
//                        overlay.animation = MTStatusBarOverlayAnimationFallDown;
//                        overlay.detailViewMode = MTDetailViewModeDetailText;
//                        overlay.delegate = nil;
//                        overlay.progress = 0.0;
//                        [overlay postFinishMessage:@"出差变更申请审批成功！" duration:1.6 animated:YES];
//                        overlay.progress = 1.8;
                        
                        [self showAlertViewWithMessage:@"出差变更申请审批成功"];
                    }
                }
            }
        }
        [self performSelector:@selector(getErandChangeApplyList) withObject:nil afterDelay:0.9];
    } else if (methodId == rejectApply) { //驳回
        if ([data isKindOfClass:[NSDictionary class]]) {
            int code = [[data objectForKeyOrNil:@"code"] integerValue];
            if (code == 0) {
                if ([data count] > 0) {
                    id dataObject = [data objectForKeyOrNil:@"data"];
                    NSInteger resultCode = [[dataObject objectForKeyOrNil:@"result"] integerValue];
                    if (resultCode == 1) {
//                        MTStatusBarOverlay *overlay = [MTStatusBarOverlay sharedInstance];
//                        overlay.animation = MTStatusBarOverlayAnimationFallDown;
//                        overlay.detailViewMode = MTDetailViewModeDetailText;
//                        overlay.delegate = nil;
//                        overlay.progress = 0.0;
//                        [overlay postFinishMessage:@"出差变更申请驳回成功！" duration:1.6 animated:YES];
//                        overlay.progress = 1.8;
                        
                        [self showAlertViewWithMessage:@"出差变更申请驳回成功"];
                    }
                }
            }
        }
        [self performSelector:@selector(getErandChangeApplyList) withObject:nil afterDelay:0.9];
    }
    
}

- (void)network:(NetworkManager *)net methodId:(RequestMethodId)methodId didRequestFailedWithError:(NSError *)error {
    [self.HUD hide:YES];
    [self endRefresh];
    self.isRefreshing = NO;
    
    NSDictionary *errorInfo = error.userInfo;
    NSString *msg = [errorInfo objectForKeyOrNil:@"errorMsg"];
    
    NSInteger code = error.code;
    if (code != 1) {
        if ([msg length] == 0) {
            if (methodId == showApplyByChangeExamine) {
                msg = @"出差变更申请列表获取失败，请稍后重试";
            } else if (methodId == leaderExamineApplyChange) {
                msg = @"出差变更申请审批失败，请稍后重试";
            } else if (methodId == rejectApply) {
                msg = @"出差变更申请驳回失败，请稍后重试";
            }
            
        }
    }
    if ([msg length] > 0) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:msg
                                                       delegate:nil
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        [alert show];
    }
    
    [self.tableView reloadData];
}

#pragma mark - UITableViewDataSource methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    [self endRefresh];
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
//    return 8;
    return [self.applyList count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellIdentifier = @"ErrandsChangeApplyCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        
    }
    
    UILabel *dudaoNameLbl = (UILabel *)[cell.contentView viewWithTag:101];
    UILabel *dudaoCodeLbl = (UILabel *)[cell.contentView viewWithTag:102];
    UILabel *dudaoDeptLbl = (UILabel *)[cell.contentView viewWithTag:103];
    UILabel *dateLbl = (UILabel *)[cell.contentView viewWithTag:104];
    UILabel *agencyNameLbl = (UILabel *)[cell.contentView viewWithTag:105];
    UILabel *agencyCodeLbl = (UILabel *)[cell.contentView viewWithTag:106];
    UILabel *reasonLbl = (UILabel *)[cell.contentView viewWithTag:107];
//    UIButton *statusBtn = (UIButton *)[cell.contentView viewWithTag:108];

    NSInteger row = indexPath.row;
    
    if ([self.applyList count] > row) {
        NSDictionary *cellData = [self.applyList objectAtIndex:row];
        
        NSString *dudaoName = [cellData objectForKeyOrNil:@"xm"];
        NSString *dudaoCode = [cellData objectForKeyOrNil:@"gh"];
        NSString *dudaoDept = [cellData objectForKeyOrNil:@"zw"];
        NSString *merchantName = [cellData objectForKeyOrNil:@"bgjxsmc"];
        NSString *merchantbgCode = [cellData objectForKeyOrNil:@"bgjxsdm"];
        NSString *merchantbgName = [cellData objectForKeyOrNil:@"jxsmc"];
        NSString *merchantCode = [cellData objectForKeyOrNil:@"jxsdm"];
        NSString *bgreason = [cellData objectForKeyOrNil:@"bgmd"];
        NSString *reason = [cellData objectForKeyOrNil:@"ccmd"];
        NSString *time = [cellData objectForKeyOrNil:@"ccsj"];
        BOOL sfbg = [[cellData objectForKeyOrNil:@"sfbg"] boolValue]; //是否变更
        dudaoNameLbl.text = dudaoName;
        dudaoCodeLbl.text = dudaoCode;
        dudaoDeptLbl.text = dudaoDept;
        dateLbl.text = time;
        NSLog(@"@@@@@@@@@%d",sfbg);
        agencyNameLbl.text = merchantName;
        agencyCodeLbl.text = merchantCode;
        reasonLbl.text = reason;
        if (sfbg) {
            agencyNameLbl.text = merchantbgName;
            agencyCodeLbl.text = merchantbgCode;
            reasonLbl.text = bgreason;
        }
        
    }
    
    return cell;
    
}

#pragma mark - UITableViewDelegate methods
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 60.0;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    self.selectedRow = indexPath.row;
    
    UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:@""
                                                       delegate:self
                                              cancelButtonTitle:@"取消"
                                         destructiveButtonTitle:nil
                                              otherButtonTitles:@"进入临店项目",@"进入详情查看",@"通过",@"驳回", nil];
    [sheet showInView:self.view];
}

#pragma mark - UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 0) { //进入临店项目
        [self enterProjectsListView];
    } else if (buttonIndex == 1) { //进入详情
        [self enterApplyDetailView];
    } else if (buttonIndex == 2) { //通过
        [self agreeErandChangeApply];
    } else if (buttonIndex == 3) { //驳回
        [self rejectErandChangeApply];
    }
}

- (void)enterProjectsListView {
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Leader" bundle:nil];
    LStoreProblemListViewController *storeProblemVC = (LStoreProblemListViewController *)[storyboard instantiateViewControllerWithIdentifier:@"LeaderStoreProblemList"];
    storeProblemVC.viewType = EnterFromCCBG; //标识从出差变更审批界面进入
        NSInteger row = self.selectedRow;
    if ([self.applyList count] > row) {
        NSDictionary *cellData = [self.applyList objectAtIndex:row];
        storeProblemVC.erandInfo = cellData;
        storeProblemVC.sfbg =[[cellData objectForKey:@"sfbg"] boolValue]; //是否变更

    }
    [self.navigationController pushViewController:storeProblemVC animated:YES];
}

//同意变更申请
- (void)agreeErandChangeApply {
    if (self.selectedRow >= 0 && [self.applyList count] > self.selectedRow) {
        NSDictionary *cellData = [self.applyList objectAtIndex:self.selectedRow];
        NSString *applyID = [cellData objectForKeyOrNil:@"id"];
        
        NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                               applyID,@"id", nil];
        [self.networkManager requestWithMethod:leaderExamineApplyChange parameter:param delegate:self];
        [self.HUD show:YES];
    }
}

//驳回变更申请
- (void)rejectErandChangeApply {
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Leader" bundle:nil];
    RejectViewController *rejectVC = (RejectViewController *)[storyboard instantiateViewControllerWithIdentifier:@"RejectViewController"];
    rejectVC.delegate = self;
    [self addChildViewController:rejectVC];
    [self.view addSubview:rejectVC.view];
}

//进入变更详情
- (void)enterApplyDetailView {
    //ErandChangeApproveDetail
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Leader" bundle:nil];
    ErandChangeApproveDetailViewController *detailVC = (ErandChangeApproveDetailViewController *)[storyboard instantiateViewControllerWithIdentifier:@"ErandChangeApproveDetail"];
    if (self.selectedRow >= 0 && [self.applyList count] > self.selectedRow) {
        NSDictionary *cellData = [self.applyList objectAtIndex:self.selectedRow];
        detailVC.erandInfo = cellData;
    }
    [self.navigationController pushViewController:detailVC animated:YES];
}

#pragma mark - RejectViewDelegate
- (void)reject:(RejectViewController *)rejectVC willRejctWithReason:(NSString *)content {
    if (self.selectedRow >= 0 && [self.applyList count] > self.selectedRow) {
        NSDictionary *cellData = [self.applyList objectAtIndex:self.selectedRow];
        NSString *applyID = [cellData objectForKeyOrNil:@"id"];
        
        NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                               applyID,@"id",
                               content,@"bhly", nil];
        [self.networkManager requestWithMethod:rejectApply parameter:param delegate:self];
        [self.HUD show:YES];
    }
}

@end
